import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Home from '@/views/home'
import Layout from '@/views/layout'
import Article from '@/views/article'
import Publish from '@/views/publish'
import Image from '@/views/image'
import Comment from '@/views/comment'
import Settings from '@/views/settings'
import Funs from '@/views/fans'

Vue.use(VueRouter)

// 路由配置表
const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    children: [
      // 首页
      {
        path: '', // path 为空，会作为默认子路由渲染
        name: 'home',
        component: Home
      },
      // 内容管理
      {
        path: '/article',
        name: 'article',
        component: Article
      },
      // 发布文章
      {
        path: '/publish',
        name: 'publish',
        component: Publish
      },
      // 素材管理
      {
        path: '/image',
        name: 'image',
        component: Image
      },
      // 评论管理
      {
        path: '/comment',
        name: 'comment',
        component: Comment
      },
      // 个人设置
      {
        path: '/settings',
        name: 'settings',
        component: Settings
      },
      // 粉丝管理
      {
        path: '/fans',
        name: 'fans',
        component: Funs
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由导航守卫(vue提供的路由页面导航拦截器)
router.beforeEach((to, from, next) => {
  // to: 目标页面路由信息
  // from: 源页面路由信息
  // next: 放行

  // 从本地存储中获取用户登录信息
  const user = JSON.parse(window.localStorage.getItem('user'))

  // 访问非登录页面，则校验登录状态
  if (to.path !== '/login') {
    if (user) {
      // 已登录则允许通过
      next()
    } else {
      // 未登录则跳转到登录页面
      next('/login')
    }
  } else {
    // 允许直接访问登录页面
    next()
  }
})

export default router
